package com.rbac.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.common.Result;
import com.rbac.entity.SysPermission;
import com.rbac.service.SysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 权限管理控制器
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/permission")
@Api(tags = "权限管理")
public class SysPermissionController {

    @Autowired
    private SysPermissionService permissionService;

    @GetMapping("/page")
    @ApiOperation("分页查询权限")
    @PreAuthorize("hasAuthority('permission:query')")
    public Result<IPage<SysPermission>> page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("权限名称") @RequestParam(required = false) String permissionName,
            @ApiParam("权限编码") @RequestParam(required = false) String permissionCode,
            @ApiParam("资源类型") @RequestParam(required = false) Integer resourceType,
            @ApiParam("状态") @RequestParam(required = false) Integer status) {
        
        Page<SysPermission> page = new Page<>(current, size);
        IPage<SysPermission> result = permissionService.page(page, permissionName, permissionCode, resourceType, status);
        return Result.success(result);
    }

    @GetMapping("/list")
    @ApiOperation("查询权限列表")
    @PreAuthorize("hasAuthority('permission:query')")
    public Result<List<SysPermission>> list() {
        List<SysPermission> list = permissionService.list();
        return Result.success(list);
    }

    @GetMapping("/tree")
    @ApiOperation("查询权限树")
    @PreAuthorize("hasAuthority('permission:query')")
    public Result<List<SysPermission>> tree() {
        List<SysPermission> tree = permissionService.getPermissionTree();
        return Result.success(tree);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询权限")
    @PreAuthorize("hasAuthority('permission:query')")
    public Result<SysPermission> getById(@ApiParam("权限ID") @PathVariable Long id) {
        SysPermission permission = permissionService.getById(id);
        if (permission == null) {
            return Result.error("权限不存在");
        }
        return Result.success(permission);
    }

    @PostMapping
    @ApiOperation("创建权限")
    @PreAuthorize("hasAuthority('permission:add')")
    public Result<String> create(@Valid @RequestBody SysPermission permission) {
        // 检查权限编码是否已存在
        if (permissionService.existsByPermissionCode(permission.getPermissionCode())) {
            return Result.error("权限编码已存在");
        }
        
        boolean success = permissionService.save(permission);
        return success ? Result.success("创建成功") : Result.error("创建失败");
    }

    @PutMapping("/{id}")
    @ApiOperation("更新权限")
    @PreAuthorize("hasAuthority('permission:edit')")
    public Result<String> update(@ApiParam("权限ID") @PathVariable Long id, @Valid @RequestBody SysPermission permission) {
        permission.setId(id);
        
        // 检查权限编码是否被其他权限使用
        if (permissionService.existsByPermissionCodeAndIdNot(permission.getPermissionCode(), id)) {
            return Result.error("权限编码已被其他权限使用");
        }
        
        boolean success = permissionService.updateById(permission);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除权限")
    @PreAuthorize("hasAuthority('permission:delete')")
    public Result<String> delete(@ApiParam("权限ID") @PathVariable Long id) {
        boolean success = permissionService.removeById(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    @GetMapping("/role/{roleId}")
    @ApiOperation("查询角色权限")
    @PreAuthorize("hasAuthority('permission:query')")
    public Result<List<SysPermission>> getPermissionsByRoleId(@ApiParam("角色ID") @PathVariable Long roleId) {
        List<SysPermission> permissions = permissionService.getPermissionsByRoleId(roleId);
        return Result.success(permissions);
    }

    @GetMapping("/user/{userId}")
    @ApiOperation("查询用户权限")
    @PreAuthorize("hasAuthority('permission:query')")
    public Result<List<SysPermission>> getPermissionsByUserId(@ApiParam("用户ID") @PathVariable Long userId) {
        List<SysPermission> permissions = permissionService.getPermissionsByUserId(userId);
        return Result.success(permissions);
    }
}
